<template>
  <a-layout-header class="global-header">
    <div class="header-container">
      <!-- 左侧 Logo、标题和菜单 -->
      <div class="header-left">
        <div class="logo-container" @click="goToHome">
          <img src="/logo.png" alt="Logo" class="logo" />
          <h1 class="site-title">AI零代码应用生成平台</h1>
        </div>

        <!-- 菜单 -->
        <div class="header-menu">
          <a-menu
            v-model:selectedKeys="selectedKeys"
            mode="horizontal"
            :items="menuItems"
            class="menu"
            @click="handleMenuClick"
          />
        </div>
      </div>

      <!-- 右侧用户信息 -->
      <div class="header-right">
        <div v-if="loginUserStore.loginUser.id">
          <a-dropdown>
            <a-space>
              <a-avatar :src="loginUserStore.loginUser.avatar" />
              {{ loginUserStore.loginUser.username ?? '无名氏' }}
            </a-space>
            <template #overlay>
              <a-menu>
                <a-menu-item @click="toUserInfo">
                  <UserOutlined />
                  个人中心
                </a-menu-item>
                <a-menu-item @click="handleLogout">
                  <LogoutOutlined />
                  退出登录
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </div>
        <div v-else>
          <a-button type="primary" @click="handleLogin">
            <template #icon>
              <UserOutlined />
            </template>
            登录
          </a-button>
        </div>
      </div>
    </div>
  </a-layout-header>
</template>

<script setup lang="ts">
import { onMounted, ref, computed } from 'vue'
import { LogoutOutlined, UserOutlined } from '@ant-design/icons-vue'
import { useRoute, useRouter } from 'vue-router'
import type { MenuProps } from 'ant-design-vue'
import { message } from 'ant-design-vue'
import { useLoginUserStore } from '@/stores/loginUser'
import checkAccess from '@/access/checkAccess'
import { routes } from '@/router/routes'

const router = useRouter()
const route = useRoute()
const loginUserStore = useLoginUserStore()

// 选中的菜单项
const selectedKeys = ref<string[]>(['/'])

// 菜单配置
const originItems = routes.map((item) => {
  // 如果有子菜单，需要处理子菜单结构
  if (item.children && item.children.length > 0) {
    return {
      key: item.path,
      label: item.label,
      icon: item.icon,
      children: item.children.map((child) => ({
        key: child.path,
        label: child.label
      })),
      meta: item.meta,
    }
  }

  return {
    key: item.path,
    label: item.label,
    icon: item.icon,
    meta: item.meta,
  }
})

// const originItems = [
//   {
//     key: '/',
//     label: '首页',
//     icon: () => h(HomeOutlined),
//   },
//   {
//     key: '/projects',
//     label: '我的项目',
//     icon: () => h(FolderOutlined),
//   },
//   {
//     key: '/templates',
//     label: '模板中心',
//     icon: () => h(FileTextOutlined),
//   },
//   {
//     key: '/docs',
//     label: '使用文档',
//     icon: () => h(BookOutlined),
//   },
//   {
//     key: '/about',
//     label: '关于',
//     icon: () => h(QuestionCircleOutlined),
//   },
//   {
//     key: '/admin',
//     label: '管理页',
//     icon: () => h(SettingOutlined),
//     children: [
//       {
//         key: '/admin/user',
//         label: '用户管理',
//       },
//     ],
//   },
// ]

// 过滤菜单项
// const filterMenus = (menus = [] as MenuProps['items']) => {
//   return menus?.filter((menu) => {
//     const menuKey = menu?.key as string
//     if (menuKey?.startsWith('/admin')) {
//       const loginUser = loginUserStore.loginUser
//       if (!loginUser || loginUser.role !== 'admin') {
//         return false
//       }
//     }
//     return true
//   })
// }

// 过滤菜单项 - 使用计算属性确保响应式更新
const menuItems = computed(() => {
  return originItems.filter((item) => {
    // 如果菜单项设置了隐藏，则不显示
    if (item.meta?.hideInMenu) {
      return false
    }

    // 根据权限过滤菜单，有权限则返回 true，则保留该菜单
    const hasAccess = checkAccess(loginUserStore.loginUser, item.meta?.access as string)

    // 如果有子菜单，也需要过滤子菜单
    if (item.children && item.children.length > 0) {
      const filteredChildren = item.children.filter(() => {
        // 这里可以根据需要添加子菜单的权限检查
        return true
      })

      // 如果过滤后没有子菜单了，则不显示父菜单
      if (filteredChildren.length === 0) {
        return false
      }

      // 更新子菜单
      item.children = filteredChildren
    }

    return hasAccess
  })
})

// 初始化选中菜单
onMounted(async () => {
  selectedKeys.value = [route.path]

  // 如果用户未登录，尝试获取用户信息
  if (!loginUserStore.loginUser.id) {
    try {
      await loginUserStore.fetchLoginUser()
    } catch (error) {
      console.log('获取用户信息失败:', error)
    }
  }
})

// 监听路由变化，更新当前选中菜单
router.afterEach((to) => {
  selectedKeys.value = [to.path]
})

// 登录处理
const handleLogin = () => {
  console.log('用户点击登录')
  // 实现登录逻辑
  router.push('/user/login')
}

//登出处理
const handleLogout = () => {
  //1. 清除全局状态管理
  loginUserStore.logoutUser()
  //2. 返回登录页面
  router.push('/user/login')
  //3. 信息提示
  message.success('登出成功!')
}

// 跳转到首页
const goToHome = () => {
  router.push('/')
}

const toUserInfo = () => {
  router.push('/user/info')
}

// 处理菜单点击
const handleMenuClick: MenuProps['onClick'] = (e) => {
  const key = e.key as string
  selectedKeys.value = [key]
  console.log('菜单点击:', key)
  // 跳转到对应页面
  router.push(key)
}
</script>

<style scoped>
.global-header {
  background: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 0;
  height: 64px;
  line-height: 64px;
}

.header-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin: 0 auto;
  padding: 0 24px;
  height: 100%;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 32px;
  flex: 1;
  min-width: 0;
  /* 允许子元素收缩 */
}

.logo-container {
  display: flex;
  align-items: center;
  gap: 12px;
  cursor: pointer;
  transition: opacity 0.3s ease;
}

.logo-container:hover {
  opacity: 0.8;
}

.logo {
  width: 32px;
  height: 32px;
}

.site-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #1890ff;
}

.header-menu {
  display: flex;
  align-items: center;
  flex: 1;
  min-width: 0;
}

.menu {
  border: none;
  background: transparent;
  flex: 1;
  min-width: 0;
}

/* 防止菜单项收缩 */
:deep(.ant-menu-horizontal) {
  flex: 1;
  min-width: 0;
}

:deep(.ant-menu-item) {
  white-space: nowrap;
  min-width: auto;
}

:deep(.ant-menu-submenu) {
  white-space: nowrap;
  min-width: auto;
}

.header-right {
  display: flex;
  align-items: center;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .header-left {
    gap: 24px;
  }

  .site-title {
    font-size: 16px;
  }
}

@media (max-width: 768px) {
  .header-container {
    padding: 0 16px;
  }

  .header-left {
    gap: 16px;
  }

  .site-title {
    font-size: 14px;
  }

  .header-menu {
    display: none;
    /* 移动端隐藏菜单，可以考虑使用抽屉菜单 */
  }
}

@media (max-width: 480px) {
  .site-title {
    display: none;
    /* 超小屏幕隐藏标题 */
  }
}
</style>
